package com.xuecheng.mybatis.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.xuecheng.commons.utils.AuthInfoHolder;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class MyBatisPlusConfig {

   private static String [] tables = new String[]{"tb_dictionary","tb_category",
           "undo_log","tb_application","tb_company","tb_resource","tb_role_resource","tb_user_role"};

   //注册mybatis的插件
   @Bean
   public MybatisPlusInterceptor mybatisPlusInterceptor() {
      MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
      //多租户插件
      interceptor.addInnerInterceptor(tenantEnterpriseInterceptor());
      //分页的插件
      interceptor.addInnerInterceptor(paginationInnerInterceptor());
      return interceptor;
   }

   //分页的插件配置
   @Bean
   public PaginationInnerInterceptor paginationInnerInterceptor() {
      return new PaginationInnerInterceptor(DbType.MYSQL);
   }

   /**
    * 多租户的插件配置
    *    getTenantId: 租户数据的来源
    *    getTenantIdColumn: 拼接的SQL语句的租户字段
    *    ignoreTable: 判断表时候需要租户配置
    */
   @Bean
   public TenantLineInnerInterceptor tenantEnterpriseInterceptor(){
      return new TenantLineInnerInterceptor(new TenantLineHandler() {
         //获取线程中的企业id
         public Expression getTenantId() {
            Long companyId = AuthInfoHolder.getCompanyId();
            if(ObjectUtil.isEmpty(companyId)) {
               return null;
            }else {
               return new StringValue(companyId.toString());
            }
         }

         //租户的字段
         public String getTenantIdColumn() {
            return "company_id";
         }

         //设置忽略的表,true忽略，false-拼接
         @Override
         public boolean ignoreTable(String tableName) {
            // 是否需要需要过滤某一张表
            if (ArrayUtil.contains(tables,tableName)){
               return true;
            }
            //拼接的sql多租户字段标示对应的值不能为空
            Expression tenantId = this.getTenantId();
            if (ObjectUtil.isEmpty((tenantId))){
               return true;
            }
            return false;
         }
      });
   }
}